#!/usr/local/bin/python
# -*- coding: utf-8 -*-
# Copyright (c) The PyAMF Project.
# See LICENSE.txt for details.

import time
import datetime
import json
import hashlib
import random
import math

def sendsocet(fp,data_json):
    if fp:
        if type(data_json)==str:
            fp.write((data_json+"###").encode())
        else:
            fp.write((json.dumps(data_json)+"###").encode())

def ip2int(ip):
    import struct,socket
    return struct.unpack("!I",socket.inet_aton(ip))[0]


def int2ip(i):
    import socket,struct
    return socket.inet_ntoa(struct.pack("!I",i))

#ip情况，主要作用是否允许这个ip登录
def ip_e(mongo,ip_str):
    cipdata=mongo.findone("c_ip",{"id":ip2int(ip_str)},{"type":True,"time1":True,"time2":True})
    if(cipdata==None):
        return True
    # 类型 0时间段 1直接封闭
    if(cipdata["type"]==1):
        return False
    else:
        dtime=time.time()
        if(dtime>cipdata["time1"] and dtime<cipdata["time2"]):
            return False
        else:
            return True
        
##关键字过滤
#def keyfilter(user_data,data,check=False):
#    """
#    * 关键字过滤
#    *
#    """
#    keyfilters=user_data.getkeylist()
#    if(type(data)!=types.UnicodeType):
#        data=unicode(data,"utf-8")
#        
#    for keys in keyfilters:
#        if(type(keyfilters[keys]["replace"])!=types.UnicodeType):
#            keyfilters[keys]["replace"]=unicode(keyfilters[keys]["replace"],"utf-8")
#            
#        if(type(keyfilters[keys]["key"])!=types.UnicodeType):
#            keyfilters[keys]["key"]=unicode(keyfilters[keys]["key"],"utf-8")
#        
#        if(check==False):
#            data=data.replace(keyfilters[keys]["key"],keyfilters[keys]["replace"])
#        else:
#            if len(data.split(keyfilters[keys]["key"]))>=2:return True
#    
#    if check==False:
#        return data
#    else:
#        return False

#禁言情况 大于0表示被禁言结束日期
def gag(mongo,user_id):
    c_gagdata=mongo.findone("c_gag",{"user_id":int(user_id)},{"time1":True,"time2":True})
    if(not c_gagdata):
        return 0
    
    dtime=time.time()
    if(dtime>c_gagdata["time2"]):
        return 0
    else:
        return c_gagdata["time2"]
            
#生成一个注册ID
def regid():
    times=time.time()
    ttt=str(times).split(".")
    return int(ttt[0]+ttt[1])

#系统时间撮
def systime(times=False):
    if(times==False):times=time.time()
    ttt=str(times).split(".")
    return int(ttt[0])

#系统时间到小时的时间撮
def Htime():
    H=time.strftime("%Y-%m-%d-%H",time.localtime(time.time()))
    Harr=H.split("-")
    
    s = datetime.datetime(int(Harr[0]),int(Harr[1]),int(Harr[2]),int(Harr[3]))
    Htime=systime(time.mktime(s.timetuple()))
    return Htime

#切割坐标
def xytoarr(xy):
    xyarr=xy.split(":")
    if(len(xyarr)>=2):
        return xyarr
    else:
        return False
    
#坐标字符串化
def xytostr(xy):
    return xy[0]+":"+xy[1]

#判断字符串是否可用
def is_str(strs):
    if(strs==None or strs==0 or strs==False  or strs==""):
        return False
    else:
        return True

#json处理，转成字典
def jsond(jsonstr):
    try:
        data_json=json.JSONDecoder().decode(jsonstr)
        if(type(data_json)==dict or type(data_json)==list):
            return data_json
    except:
        print("error json")
    return False

def in_array(value,arrlit):
    if(type(arrlit)==list):
        for key in arrlit:
            if(value==key):
                return True
        return False
    else:
        for key in arrlit:
            if(value==arrlit[key]):
                return True
        return False

#判断数组键值或数组是否空
def is_arr(arr,key=False):
    if(arr==False):
        return False
    if(type(arr)==list):
        if(type(key)==bool):
            return True
        else:
            if(key>=len(arr)):
                return False
            else:
                return True
        
    if(type(arr)==dict):
        if(type(key)==bool):
            if(len(arr)):
                return True
            else:
                return False
        else:
            if (key in arr):
                return True
            else:
                return False
    else:
        return False
    
#判断是否数字
def is_numeric(number):
    if(number!=0 and number==False or number==None or number==""):
        return False
    number_list={"0":True,"1":True,"2":True,"3":True,"4":True,"5":True,"6":True,"7":True,"8":True,"9":True,".":True}
    number=str(number)
    if(len(number.split("."))>2):
        return False
    
    for i in range(len(number)):
        if is_arr(number_list,number[i])==False:
            return False
    return True

#数组合并 返回一个数组，该数组包括了所有在 arr1 和arr2中的数据，如果两者键名相同者用arr2覆盖arr1
def arrunite(arr1,arr2):
    for key in arr2:
        value=arr2[key]
        if(is_arr(value)):
            arrunite(arr1[key],value)
        arr1[key]=value;
    return arr1;

        
#主要功能是将关键字补充道传入的字符串中
def keys(strs,check=False):
    ics={}
    keyc_={}
    keyc={}
    i=0
    ics_arr=ics.split("\r\n")
    if(len(ics_arr)==1):
        ics_arr=ics.split("\n")
    
    if(check==False):
        #直接替换
        for key in ics_arr:
            value=ics_arr[key]
            keyc[i]='/'+value+'/';
            keyc_[i]="***";
            i+=1
            
        return strs.replace(keyc, keyc_)
    else:  #只检查不替换
        for key in ics_arr:
            value=ics_arr[key]
            if(value):
                if len(strs.split(value))>=2:
                    return False    #有非法关键字
        return True #没有非法关键字
    
#md5的实现
def mymd5(strs):
    if(is_str(strs)):
        strs=bytes(str(strs))
        strs=hashlib.md5(strs).hexdigest()
    return strs

#md5的实现
def nmd5(strs):
    if(is_str(strs)):
        m = hashlib.md5()
        m.update(strs)
        strs=m.hexdigest()
    return strs


def get_w_p(probability):
    """
    描述：取得小数位数
    参数：
    probability 随机率
    返回值 ：int
    """
    probability=round(probability,5)
    tmp=str(probability).split(".")
    t=len(tmp[1])
    if t==1:
        ts=10
    if t==2:
        ts=100
    if t==3:
        ts=1000
    if t==4:
        ts=10000
    if t==5:
        ts=100000
    if t==6:
        ts=1000000
    return ts


def rand_p(probability,maxs=100):
    """
    描述：随机率
    参数：
    probability 随机率
    maxs 概率值比如 100，1000，10000等
    返回值 ：int
    """
    if(is_numeric(probability)==False):return False
    if(type(probability)!=int and type(probability)!=float):
        probability=float(probability)
        
    tmpprob=probability*maxs
    if(tmpprob<1):
    #如果还是小于1，说明maxs参数有误，这里可以修正这个参数,但效率上可能有些损失
        maxs=get_w_p(probability)
        tmpprob=probability*maxs
    
    maxs-=1
    m=random.randint(0,int(maxs))
    
    if(m<=int(tmpprob)):
        return True
    else:
        return False
    

def rand_dict(dic):
    """
    描述：字典模式随机
    参数：
    dic 随机率 {"a":0.005,"b":0.658,"c":20.24}长度不定，根据需要
    返回值 ：key或者False
    """
    for key in dic:
        if rand_p(dic[key]):
            return key
    return False
    

def key(arr):
    """
    描述：返回第一个KEY
    参数：
    arr 字典或数组
    返回值 ：key或者False
    """
    if(is_arr(arr)==False):
        return False
    
    for k in arr:
        return k
    

def array_rand(arr):
    """
    描述：从数组中随机一个数据
    参数：
    arr 数组
    返回值 ：value或者False
    """
    if(is_arr(arr)==False):
        return False
    
    m=random.randint(0,len(arr)-1)
    return arr[m]

def distance(xy1,xy2):
    """
    求两点距离
    坐标格式如：55:78
    $xy1 自己坐标
    $xy2 对方坐标
    """
    xy1=xy1.split(':')
    xy2=xy2.split(':')
    var = round(math.sqrt(pow((int(xy2[0])-int(xy1[0])),2)+pow((int(xy2[1])-int(xy1[1])),2)))
    return var

#对象序列化成数组
def array_keys(arr):
    n={}
    for key in arr:
        n[len(n)]=key
    return n 


def getonestr(strs):
    """
    @取得第一个中文
    @param string str 字符串
    @return  string
    """
    if (ord(strs[0])>127): #中文
        return strs[:4]
    else:#非中文
        return strs[:1]
    

def hour(e=False):
    if(e=="H"):
        re=time.strftime("%H",time.localtime(time.time()))
    elif(e=="H:i"):
        re=time.strftime("%H:%i",time.localtime(time.time()))
    else:
        re=time.strftime("%H:%i:%s",time.localtime(time.time()))
    return re

#取得星期几 $data 2009-10-10
def week():
    re=time.strftime("%w",time.localtime(time.time()))
    return int(re)

#取得本周过期日期
def week_go():
    tmpw=7-int(week())
    today = datetime.date.today()
    oneday = datetime.timedelta(days=tmpw)
    yesterday = today - oneday
    tommorrow = today + oneday
    return str(yesterday)+str(today)+str(tommorrow)


def spage(arr,page,currentPage=0):
    """
    散装分页函数
    $arr 需要分页的数组
    $page  每页记录数
    $currentPage要取那也的数据
    返回:array(
    content=>内容,
    currentPage =>第几页,
    totalPage=>共几页,
    )
    """
    arr1={}
    arr_={}
    atr={}
    for k in arr:
        v=arr[k]
        arr1[len(arr1)] = v
        
    sums=len(arr1)
    #取得总页数
    if(sums%page==0):
        totalPage=int(sums/page)
    else:
        totalPage=int(sums/page)+1
    
    if(currentPage):
        dp=currentPage-1
    else:
        dp=0
    if(dp*page+page<sums):
        sums=dp*page+page
        
    for i in range(dp*page,sums):
        atr[len(atr)]=arr1[i]
              
    arr_['content']=atr
    if(currentPage<1):
        currentPage=1
    else:
        currentPage=currentPage
    if(currentPage>totalPage):
        currentPage=totalPage
    else:
        totalPage=currentPage
        
    if(currentPage ==0):
        arr_['currentPage'] =1
    else:
        arr_['currentPage']=currentPage#第几页
        
    arr_['totalPage']=totalPage#共X页
    
    return arr_

#排序
def keyintsort(arr):
    ne={}
    e=sorted(arr.items(), key=lambda d: d[0],reverse=True)
        
    for key in e:
        ne[int(key[0])]=key[1]
    return ne

def myinitialize(arr,key,defaults={}):
    """
    * 数据初始化
    *
    * @param array arr 检测数组
    * @param string key 检测数组存在的key
    * @param Unknown defaults 如果没有就默认
    """
    if is_arr(arr,key)==False:
        return defaults
    else:
        if(is_str(arr[key])==False):
            return defaults
        else:
            return arr[key]
        

def today():
    """
    * 当天日期 (年月日)
    *
    """
    return time.strftime("%Y%m%d",time.localtime(time.time()))

#def cnstr(**arg):
#    """
#    * 中文字符串编码处理
#    *
#    """
#    tmparr = {}
#    tmpstr=""
#    leng=len(arg)
#    if len(arg) == 0: 
#        return 0
#    else:
#        for s in arg:
#            leng-=1
#            if(type(arg[s])!=str):
#                arg[s]=str(arg[s])
#            tmparr[leng]=arg[s]
#            
#        for x in tmparr:
#            if(type(tmparr[x])!=str):
#                tmparr[x]=str(tmparr[x])
#            tmpstr+=tmparr[x]
#    return tmpstr

def xrun(cimport,classs,funcname,parameter=False):
    """
    @info 调用其他模块的函数
    @param string cimport 引入路径
    @param string classs  类名
    @param array funcname 函数名
    @param array parameter 外部存入一个数组 可选
    @return key False
    """
    mymodule=__import__(cimport, globals(), locals(),[funcname], -1)
                
    if(classs):
        funcs=getattr(getattr(mymodule,classs)(),funcname, None)
    else:
        funcs=getattr(mymodule,funcname, None)
        
    if funcs:
        funcs(parameter)
        return True
    else:
        return False
    